/* ********************************************************** */
/* * Monte Carlo Method for finding PI - Sequential Version * */
/* ********************************************************** */

#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "../include/rand.h"

/* Default values */
#define DEFAULT_ATTEMPTS 1000000000

/* Try function: Randomly place a dot inside a square/circle with diameter/length of 1 unit. Return true if dot is inside the circle */
bool try(unsigned int seed) {
	double x, y;

	/* Randomly pick x coordinate */
	unsigned int randVal = randNext(seed) % UINT_MAX;
	x = (double) randVal / UINT_MAX;

	/* Randomly pick y coordinate */
	randVal = randNext(randVal) % UINT_MAX;
	y = (double) randVal / UINT_MAX;

	/* Return true if dot is inside the circle */
	return ((pow(x,2) + pow(y,2)) <= 1.0)? 1 : 0;
}

int main(int argc, char *argv[]) {
	/* If no argument is passed, load default setting for attempts */
	int i, hits, attempts = (2 != argc)? DEFAULT_ATTEMPTS : atoi(argv[1]);
	double pi;
	time_t timeSeed = time(NULL);

	/* Run try() sequentially */
	for(i = 0; i < attempts; i++)
		hits += try(i*timeSeed);

	/* Calculate PI using Monte Carlo */
	pi = (4.0 * hits) / attempts;
	printf("PI=%.6lf\n", pi);

	return 0;
}